/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 *   Mupen64plus/PCSX - assem_arm64.c                                      *
 *   Copyright (C) 2009-2011 Ari64                                         *
 *   Copyright (C) 2009-2018 Gillou68310                                   *
 *   Copyright (C) 2021 notaz                                              *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.          *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

#include "pcnt.h"
#include "arm_features.h"

/* Linker */
static void set_jump_target(void *addr, void *target)
{
  u_int *ptr = NDRC_WRITE_OFFSET(addr);
  intptr_t offset = (u_char *)target - (u_char *)addr;

  if ((*ptr&0xFC000000) == 0x14000000) { // b
    assert(offset>=-134217728LL&&offset<134217728LL);
    *ptr=(*ptr&0xFC000000)|((offset>>2)&0x3ffffff);
  }
  else if ((*ptr&0xff000000) == 0x54000000 // b.cond
        || (*ptr&0x7e000000) == 0x34000000) { // cbz/cbnz
    // Conditional branch are limited to +/- 1MB
    // block max size is 256k so branching beyond the +/- 1MB limit
    // should only happen when jumping to an already compiled block (see add_jump_out)
    // a workaround would be to do a trampoline jump via a stub at the end of the block
    assert(-1048576 <= offset && offset < 1048576);
    *ptr=(*ptr&0xFF00001F)|(((offset>>2)&0x7ffff)<<5);
  }
  else if((*ptr&0x9f000000)==0x10000000) { // adr
    // generated by do_miniht_insert
    assert(offset>=-1048576LL&&offset<1048576LL);
    *ptr=(*ptr&0x9F00001F)|(offset&0x3)<<29|((offset>>2)&0x7ffff)<<5;
  }
  else
    abort(); // should not happen
}

// from a pointer to external jump stub (which was produced by emit_extjump2)
// find where the jumping insn is
static void *find_extjump_insn(void *stub)
{
  int *ptr = (int *)stub + 2;
  assert((*ptr&0x9f000000) == 0x10000000); // adr
  int offset = (((signed int)(*ptr<<8)>>13)<<2)|((*ptr>>29)&0x3);
  return ptr + offset / 4;
}

#if 0
// find where external branch is liked to using addr of it's stub:
// get address that the stub loads (dyna_linker arg1),
// treat it as a pointer to branch insn,
// return addr where that branch jumps to
static void *get_pointer(void *stub)
{
  int *i_ptr = find_extjump_insn(stub);
  if ((*i_ptr&0xfc000000) == 0x14000000)  // b
    return i_ptr + ((signed int)(*i_ptr<<6)>>6);
  if ((*i_ptr&0xff000000) == 0x54000000     // b.cond
      || (*i_ptr&0x7e000000) == 0x34000000) // cbz/cbnz
    return i_ptr + ((signed int)(*i_ptr<<8)>>13);
  assert(0);
  return NULL;
}
#endif

// Allocate a specific ARM register.
static void alloc_arm_reg(struct regstat *cur,int i,signed char reg,int hr)
{
  int n;
  int dirty=0;

  // see if it's already allocated (and dealloc it)
  for(n=0;n<HOST_REGS;n++)
  {
    if(n!=EXCLUDE_REG&&cur->regmap[n]==reg) {
      dirty=(cur->dirty>>n)&1;
      cur->regmap[n]=-1;
    }
  }

  cur->regmap[hr]=reg;
  cur->dirty&=~(1<<hr);
  cur->dirty|=dirty<<hr;
  cur->isconst&=~(1<<hr);
}

// Alloc cycle count into dedicated register
static void alloc_cc(struct regstat *cur, int i)
{
  alloc_arm_reg(cur, i, CCREG, HOST_CCREG);
}

static void alloc_cc_optional(struct regstat *cur, int i)
{
  if (cur->regmap[HOST_CCREG] < 0) {
    alloc_arm_reg(cur, i, CCREG, HOST_CCREG);
    cur->noevict &= ~(1u << HOST_CCREG);
  }
}

/* Special alloc */


/* Assembler */

static attr_unused const char *regname[32] = {
  "w0",  "w1",  "w2",  "w3",  "w4",  "w5",  "w6",  "w7",
  "w8",  "w9", "w10", "w11", "w12", "w13", "w14", "w15",
 "ip0", "ip1", "w18", "w19", "w20", "w21", "w22", "w23",
 "w24", "w25", "w26", "w27", "w28", "wfp", "wlr", "wsp"
};

static attr_unused const char *regname64[32] = {
  "x0",  "x1",  "x2",  "x3",  "x4",  "x5",  "x6",  "x7",
  "x8",  "x9", "x10", "x11", "x12", "x13", "x14", "x15",
 "ip0", "ip1", "x18", "x19", "x20", "x21", "x22", "x23",
 "x24", "x25", "x26", "x27", "x28",  "fp",  "lr",  "sp"
};

enum {
  COND_EQ, COND_NE, COND_CS, COND_CC, COND_MI, COND_PL, COND_VS, COND_VC,
  COND_HI, COND_LS, COND_GE, COND_LT, COND_GT, COND_LE, COND_AW, COND_NV
};

static attr_unused const char *condname[16] = {
  "eq", "ne", "cs", "cc", "mi", "pl", "vs", "vc",
  "hi", "ls", "ge", "lt", "gt", "le", "aw", "nv"
};

static void output_w32(u_int word)
{
  *((u_int *)NDRC_WRITE_OFFSET(out)) = word;
  out += 4;
}

static u_int rn_rd(u_int rn, u_int rd)
{
  assert(rn < 31);
  assert(rd < 31);
  return (rn << 5) | rd;
}

static u_int rm_rn_rd(u_int rm, u_int rn, u_int rd)
{
  assert(rm < 32);
  assert(rn < 32);
  assert(rd < 32);
  return (rm << 16) | (rn << 5) | rd;
}

static u_int rm_ra_rn_rd(u_int rm, u_int ra, u_int rn, u_int rd)
{
  assert(ra < 32);
  return rm_rn_rd(rm, rn, rd) | (ra << 10);
}

static u_int imm7_rt2_rn_rt(u_int imm7, u_int rt2, u_int rn, u_int rt)
{
  assert(imm7 < 0x80);
  assert(rt2 < 31);
  assert(rn < 32);
  assert(rt < 31);
  return (imm7 << 15) | (rt2 << 10) | (rn << 5) | rt;
}

static u_int rm_imm6_rn_rd(u_int rm, u_int imm6, u_int rn, u_int rd)
{
  assert(imm6 <= 63);
  return rm_rn_rd(rm, rn, rd) | (imm6 << 10);
}

static u_int imm16_rd(u_int imm16, u_int rd)
{
  assert(imm16 < 0x10000);
  assert(rd < 31);
  return (imm16 << 5) | rd;
}

static u_int imm12_rn_rd(u_int imm12, u_int rn, u_int rd)
{
  assert(imm12 < 0x1000);
  assert(rn < 32);
  assert(rd < 32);
  return (imm12 << 10) | (rn << 5) | rd;
}

static u_int imm9_rn_rt(u_int imm9, u_int rn, u_int rd)
{
  assert(imm9 < 0x200);
  assert(rn < 31);
  assert(rd < 31);
  return (imm9 << 12) | (rn << 5) | rd;
}

static u_int imm19_rt(u_int imm19, u_int rt)
{
  assert(imm19 < 0x80000);
  assert(rt < 31);
  return (imm19 << 5) | rt;
}

static u_int n_immr_imms_rn_rd(u_int n, u_int immr, u_int imms, u_int rn, u_int rd)
{
  assert(n < 2);
  assert(immr < 0x40);
  assert(imms < 0x40);
  assert(rn < 32);
  assert(rd < 32);
  return (n << 22) | (immr << 16) | (imms << 10) | (rn << 5) | rd;
}

static u_int genjmp(const u_char *addr)
{
  intptr_t offset = addr - out;
  if ((uintptr_t)addr < 3) return 0; // a branch that will be patched later
  if (offset < -134217728 || offset > 134217727) {
    SysPrintf("%s: out of range: %p %lx\n", __func__, addr, offset);
    abort();
    return 0;
  }
  return ((u_int)offset >> 2) & 0x03ffffff;
}

static u_int genjmpcc(const u_char *addr)
{
  intptr_t offset = addr - out;
  if ((uintptr_t)addr < 3) return 0;
  if (offset < -1048576 || offset > 1048572) {
    SysPrintf("%s: out of range: %p %lx\n", __func__, addr, offset);
    abort();
    return 0;
  }
  return ((u_int)offset >> 2) & 0x7ffff;
}

static uint32_t is_mask(u_int value)
{
  return value && ((value + 1) & value) == 0;
}

// This function returns true if the argument contains a
// non-empty sequence of ones (possibly rotated) with the remainder zero.
static uint32_t is_rotated_mask(u_int value)
{
  if (value == 0 || value == ~0)
    return 0;
  if (is_mask((value - 1) | value))
    return 1;
  return is_mask((~value - 1) | ~value);
}

static void gen_logical_imm(u_int value, u_int *immr, u_int *imms)
{
  int lzeros, tzeros, ones;
  assert(value != 0);
  if (is_mask((value - 1) | value)) {
    lzeros = __builtin_clz(value);
    tzeros = __builtin_ctz(value);
    ones = 32 - lzeros - tzeros;
    *immr = (32 - tzeros) & 31;
    *imms = ones - 1;
    return;
  }
  value = ~value;
  if (is_mask((value - 1) | value)) {
    lzeros = __builtin_clz(value);
    tzeros = __builtin_ctz(value);
    ones = 32 - lzeros - tzeros;
    *immr = lzeros;
    *imms = 31 - ones;
    return;
  }
  abort();
}

static void emit_mov(u_int rs, u_int rt)
{
  assem_debug("mov %s,%s\n", regname[rt], regname[rs]);
  output_w32(0x2a000000 | rm_rn_rd(rs, WZR, rt));
}

static void emit_mov64(u_int rs, u_int rt)
{
  assem_debug("mov %s,%s\n", regname64[rt], regname64[rs]);
  output_w32(0xaa000000 | rm_rn_rd(rs, WZR, rt));
}

static void emit_add(u_int rs1, u_int rs2, u_int rt)
{
  assem_debug("add %s,%s,%s\n", regname[rt], regname[rs1], regname[rs2]);
  output_w32(0x0b000000 | rm_rn_rd(rs2, rs1, rt));
}

static void emit_adds(u_int rs1, u_int rs2, u_int rt)
{
  assem_debug("adds %s,%s,%s\n", regname[rt], regname[rs1], regname[rs2]);
  output_w32(0x2b000000 | rm_rn_rd(rs2, rs1, rt));
}

static void emit_add64(u_int rs1, u_int rs2, u_int rt)
{
  assem_debug("add %s,%s,%s\n", regname64[rt], regname64[rs1], regname64[rs2]);
  output_w32(0x8b000000 | rm_rn_rd(rs2, rs1, rt));
}

static void emit_adds64(u_int rs1, u_int rs2, u_int rt)
{
  assem_debug("adds %s,%s,%s\n",regname64[rt],regname64[rs1],regname64[rs2]);
  output_w32(0xab000000 | rm_rn_rd(rs2, rs1, rt));
}
#define emit_adds_ptr emit_adds64

static void emit_add_lsrimm(u_int rs1, u_int rs2, u_int shift, u_int rt)
{
  assem_debug("add %s,%s,%s,lsr #%u\n",regname[rt],regname[rs1],regname[rs2],shift);
  output_w32(0x0b400000 | rm_imm6_rn_rd(rs2, shift, rs1, rt));
}

static void emit_neg(u_int rs, u_int rt)
{
  assem_debug("neg %s,%s\n",regname[rt],regname[rs]);
  output_w32(0x4b000000 | rm_rn_rd(rs, WZR, rt));
}

static void emit_negs(u_int rs, u_int rt)
{
  assem_debug("negs %s,%s\n",regname[rt],regname[rs]);
  output_w32(0x6b000000 | rm_rn_rd(rs, WZR, rt));
}

static void emit_sub(u_int rs1, u_int rs2, u_int rt)
{
  assem_debug("sub %s,%s,%s\n", regname[rt], regname[rs1], regname[rs2]);
  output_w32(0x4b000000 | rm_imm6_rn_rd(rs2, 0, rs1, rt));
}

static void emit_subs(u_int rs1, u_int rs2, u_int rt)
{
  assem_debug("subs %s,%s,%s\n", regname[rt], regname[rs1], regname[rs2]);
  output_w32(0x6b000000 | rm_imm6_rn_rd(rs2, 0, rs1, rt));
}

static attr_unused void emit_sub_asrimm(u_int rs1, u_int rs2, u_int shift, u_int rt)
{
  assem_debug("sub %s,%s,%s,asr #%u\n",regname[rt],regname[rs1],regname[rs2],shift);
  output_w32(0x4b800000 | rm_imm6_rn_rd(rs2, shift, rs1, rt));
}

static void emit_movz(u_int imm, u_int rt)
{
  assem_debug("movz %s,#%#x\n", regname[rt], imm);
  output_w32(0x52800000 | imm16_rd(imm, rt));
}

static void emit_movz_lsl16(u_int imm, u_int rt)
{
  assem_debug("movz %s,#%#x,lsl #16\n", regname[rt], imm);
  output_w32(0x52a00000 | imm16_rd(imm, rt));
}

static void emit_movn(u_int imm, u_int rt)
{
  assem_debug("movn %s,#%#x\n", regname[rt], imm);
  output_w32(0x12800000 | imm16_rd(imm, rt));
}

static void emit_movn_lsl16(u_int imm,u_int rt)
{
  assem_debug("movn %s,#%#x,lsl #16\n", regname[rt], imm);
  output_w32(0x12a00000 | imm16_rd(imm, rt));
}

static void emit_movk(u_int imm,u_int rt)
{
  assem_debug("movk %s,#%#x\n", regname[rt], imm);
  output_w32(0x72800000 | imm16_rd(imm, rt));
}

static void emit_movk_lsl16(u_int imm,u_int rt)
{
  assert(imm<65536);
  assem_debug("movk %s,#%#x,lsl #16\n", regname[rt], imm);
  output_w32(0x72a00000 | imm16_rd(imm, rt));
}

static void emit_zeroreg(u_int rt)
{
  emit_movz(0, rt);
}

static void emit_movimm(u_int imm, u_int rt)
{
  if (imm < 65536)
    emit_movz(imm, rt);
  else if ((~imm) < 65536)
    emit_movn(~imm, rt);
  else if ((imm&0xffff) == 0)
    emit_movz_lsl16(imm >> 16, rt);
  else if (((~imm)&0xffff) == 0)
    emit_movn_lsl16(~imm >> 16, rt);
  else if (is_rotated_mask(imm)) {
    u_int immr, imms;
    gen_logical_imm(imm, &immr, &imms);
    assem_debug("orr %s,wzr,#%#x\n", regname[rt], imm);
    output_w32(0x32000000 | n_immr_imms_rn_rd(0, immr, imms, WZR, rt));
  }
  else {
    emit_movz(imm & 0xffff, rt);
    emit_movk_lsl16(imm >> 16, rt);
  }
}

static void emit_movimm64(uint64_t imm, u_int rt)
{
  u_int shift, op, imm16, insns = 0;
  for (shift = 0; shift < 4; shift++) {
    imm16 = (imm >> shift * 16) & 0xffff;
    if (!imm16)
      continue;
    op = insns ? 0xf2800000 : 0xd2800000;
    assem_debug("mov%c %s,#%#x", insns ? 'k' : 'z', regname64[rt], imm16);
    if (shift)
      assem_debug(",lsl #%u", shift * 16);
    assem_debug("\n");
    output_w32(op | (shift << 21) | imm16_rd(imm16, rt));
    insns++;
  }
  if (!insns) {
    assem_debug("movz %s,#0\n", regname64[rt]);
    output_w32(0xd2800000 | imm16_rd(0, rt));
  }
}

static void emit_readword(void *addr, u_int rt)
{
  uintptr_t offset = (u_char *)addr - (u_char *)&dynarec_local;
  if (!(offset & 3) && offset <= 16380) {
    assem_debug("ldr %s,[x%d+%#lx]%s\n", regname[rt], FP, offset, fpofs_name(offset));
    output_w32(0xb9400000 | imm12_rn_rd(offset >> 2, FP, rt));
  }
  else
    abort();
}

static void emit_readdword(void *addr, u_int rt)
{
  uintptr_t offset = (u_char *)addr - (u_char *)&dynarec_local;
  if (!(offset & 7) && offset <= 32760) {
    assem_debug("ldr %s,[x%d+%#lx]%s\n", regname64[rt], FP, offset, fpofs_name(offset));
    output_w32(0xf9400000 | imm12_rn_rd(offset >> 3, FP, rt));
  }
  else
    abort();
}
#define emit_readptr emit_readdword

static void emit_readshword(void *addr, u_int rt)
{
  uintptr_t offset = (u_char *)addr - (u_char *)&dynarec_local;
  if (!(offset & 1) && offset <= 8190) {
    assem_debug("ldrsh %s,[x%d+%#lx]\n", regname[rt], FP, offset);
    output_w32(0x79c00000 | imm12_rn_rd(offset >> 1, FP, rt));
  }
  else
    assert(0);
}

static void emit_loadreg(u_int r, u_int hr)
{
  int is64 = 0;
  if (r == 0)
    emit_zeroreg(hr);
  else {
    void *addr;
    switch (r) {
    //case HIREG: addr = &hi; break;
    //case LOREG: addr = &lo; break;
    case CCREG: addr = &cycle_count; break;
    case INVCP: addr = &invc_ptr; is64 = 1; break;
    case ROREG: addr = &ram_offset; is64 = 1; break;
    default:
      assert(r < 34);
      addr = &psxRegs.GPR.r[r];
      break;
    }
    if (is64)
      emit_readdword(addr, hr);
    else
      emit_readword(addr, hr);
  }
}

static void emit_writeword(u_int rt, void *addr)
{
  uintptr_t offset = (u_char *)addr - (u_char *)&dynarec_local;
  if (!(offset & 3) && offset <= 16380) {
    assem_debug("str %s,[x%d+%#lx]%s\n", regname[rt], FP, offset, fpofs_name(offset));
    output_w32(0xb9000000 | imm12_rn_rd(offset >> 2, FP, rt));
  }
  else
    assert(0);
}

static void emit_writedword(u_int rt, void *addr)
{
  uintptr_t offset = (u_char *)addr - (u_char *)&dynarec_local;
  if (!(offset & 7) && offset <= 32760) {
    assem_debug("str %s,[x%d+%#lx]%s\n", regname64[rt], FP, offset, fpofs_name(offset));
    output_w32(0xf9000000 | imm12_rn_rd(offset >> 3, FP, rt));
  }
  else
    abort();
}

static void emit_storereg(u_int r, u_int hr)
{
  assert(r < 64);
  void *addr = &psxRegs.GPR.r[r];
  switch (r) {
  //case HIREG: addr = &hi; break;
  //case LOREG: addr = &lo; break;
  case CCREG: addr = &cycle_count; break;
  default: assert(r < 34); break;
  }
  emit_writeword(hr, addr);
}

static void emit_test(u_int rs, u_int rt)
{
  assem_debug("tst %s,%s\n", regname[rs], regname[rt]);
  output_w32(0x6a000000 | rm_rn_rd(rt, rs, WZR));
}

static void emit_testimm(u_int rs, u_int imm)
{
  u_int immr, imms;
  assem_debug("tst %s,#%#x\n", regname[rs], imm);
  assert(is_rotated_mask(imm)); // good enough for PCSX
  gen_logical_imm(imm, &immr, &imms);
  output_w32(0x72000000 | n_immr_imms_rn_rd(0, immr, imms, rs, WZR));
}

static void emit_not(u_int rs,u_int rt)
{
  assem_debug("mvn %s,%s\n",regname[rt],regname[rs]);
  output_w32(0x2a200000 | rm_rn_rd(rs, WZR, rt));
}

static void emit_and(u_int rs1,u_int rs2,u_int rt)
{
  assem_debug("and %s,%s,%s\n",regname[rt],regname[rs1],regname[rs2]);
  output_w32(0x0a000000 | rm_rn_rd(rs2, rs1, rt));
}

static void emit_or(u_int rs1,u_int rs2,u_int rt)
{
  assem_debug("orr %s,%s,%s\n",regname[rt],regname[rs1],regname[rs2]);
  output_w32(0x2a000000 | rm_rn_rd(rs2, rs1, rt));
}

static void emit_bic(u_int rs1,u_int rs2,u_int rt)
{
  assem_debug("bic %s,%s,%s\n",regname[rt],regname[rs1],regname[rs2]);
  output_w32(0x0a200000 | rm_rn_rd(rs2, rs1, rt));
}

static void emit_orrshl_imm(u_int rs,u_int imm,u_int rt)
{
  assem_debug("orr %s,%s,%s,lsl #%d\n",regname[rt],regname[rt],regname[rs],imm);
  output_w32(0x2a000000 | rm_imm6_rn_rd(rs, imm, rt, rt));
}

static void emit_orrshr_imm(u_int rs,u_int imm,u_int rt)
{
  assem_debug("orr %s,%s,%s,lsr #%d\n",regname[rt],regname[rt],regname[rs],imm);
  output_w32(0x2a400000 | rm_imm6_rn_rd(rs, imm, rt, rt));
}

static void emit_orn_asrimm(u_int rs1, u_int rs2, u_int shift, u_int rt)
{
  assem_debug("orn %s,%s,%s,asr #%u\n",regname[rt],regname[rs1],regname[rs2],shift);
  output_w32(0x2aa00000 | rm_imm6_rn_rd(rs2, shift, rs1, rt));
}

static void emit_bicsar_imm(u_int rs,u_int imm,u_int rt)
{
  assem_debug("bic %s,%s,%s,asr #%d\n",regname[rt],regname[rt],regname[rs],imm);
  output_w32(0x0aa00000 | rm_imm6_rn_rd(rs, imm, rt, rt));
}

static void emit_xor(u_int rs1,u_int rs2,u_int rt)
{
  assem_debug("eor %s,%s,%s\n",regname[rt],regname[rs1],regname[rs2]);
  output_w32(0x4a000000 | rm_rn_rd(rs2, rs1, rt));
}

static void emit_xorsar_imm(u_int rs1, u_int rs2, u_int imm, u_int rt)
{
  assem_debug("eor %s,%s,%s,asr #%d\n",regname[rt],regname[rs1],regname[rs2],imm);
  output_w32(0x4a800000 | rm_imm6_rn_rd(rs2, imm, rs1, rt));
}

static void emit_addimm_s(u_int s, u_int is64, u_int rs, uintptr_t imm, u_int rt)
{
  attr_unused const char *st = s ? "s" : "";
  s = s ? 0x20000000 : 0;
  is64 = is64 ? 0x80000000 : 0;
  if (imm < 4096) {
    assem_debug("add%s %s,%s,%#lx\n", st, regname[rt], regname[rs], imm);
    output_w32(0x11000000 | is64 | s | imm12_rn_rd(imm, rs, rt));
  }
  else if (-imm < 4096) {
    assem_debug("sub%s %s,%s,%#lx\n", st, regname[rt], regname[rs], -imm);
    output_w32(0x51000000 | is64 | s | imm12_rn_rd(-imm, rs, rt));
  }
  else if (imm < 16777216 && (!(imm & 0xfff) || !s)) {
    assem_debug("add%s %s,%s,#%#lx\n", st, regname[rt], regname[rs], imm&0xfff000);
    output_w32(0x11400000 | is64 | s | imm12_rn_rd(imm >> 12, rs, rt));
    if (imm & 0xfff) {
      assem_debug("add %s,%s,#%#lx\n", regname[rt], regname[rt], imm&0xfff);
      output_w32(0x11000000 | is64 | imm12_rn_rd(imm & 0xfff, rt, rt));
    }
  }
  else if (-imm < 16777216 && (!(-imm & 0xfff) || !s)) {
    assem_debug("sub%s %s,%s,#%#lx\n", st, regname[rt], regname[rs], -imm&0xfff000);
    output_w32(0x51400000 | is64 | s | imm12_rn_rd(-imm >> 12, rs, rt));
    if (-imm & 0xfff) {
      assem_debug("sub %s,%s,#%#lx\n", regname[rt], regname[rt], -imm&0xfff);
      output_w32(0x51000000 | is64 | imm12_rn_rd(-imm & 0xfff, rt, rt));
    }
  }
  else {
    u_int tmp = rt;
    assert(!is64);
    if (rs == rt) {
      host_tempreg_acquire();
      tmp = HOST_TEMPREG;
    }
    emit_movimm(imm, tmp);
    assem_debug("add%s %s,%s,%s\n", st, regname[rt], regname[rs], regname[tmp]);
    output_w32(0x0b000000 | s | rm_rn_rd(rs, tmp, rt));
    if (tmp == HOST_TEMPREG)
      host_tempreg_release();
  }
}

static void emit_addimm(u_int rs, uintptr_t imm, u_int rt)
{
  if (imm == 0) {
    emit_mov(rs, rt);
    return;
  }
  emit_addimm_s(0, 0, rs, imm, rt);
}

static void emit_addimm64(u_int rs, uintptr_t imm, u_int rt)
{
  emit_addimm_s(0, 1, rs, imm, rt);
}

static void emit_addimm_ptr(u_int rs, uintptr_t imm, u_int rt)
{
  emit_addimm64(rs, imm, rt);
}

static void emit_addimm_and_set_flags(int imm, u_int rt)
{
  emit_addimm_s(1, 0, rt, imm, rt);
}

static void emit_addimm_and_set_flags3(u_int rs, int imm, u_int rt)
{
  emit_addimm_s(1, 0, rs, imm, rt);
}

static void emit_logicop_imm(u_int op, u_int rs, u_int imm, u_int rt)
{
  const char *names[] = { "and", "orr", "eor", "ands" };
  const char *name = names[op];
  u_int immr, imms;
  op = op << 29;
  if (is_rotated_mask(imm)) {
    gen_logical_imm(imm, &immr, &imms);
    assem_debug("%s %s,%s,#%#x\n", name, regname[rt], regname[rs], imm);
    output_w32(op | 0x12000000 | n_immr_imms_rn_rd(0, immr, imms, rs, rt));
  }
  else {
    if (rs == HOST_TEMPREG || rt != HOST_TEMPREG)
      host_tempreg_acquire();
    emit_movimm(imm, HOST_TEMPREG);
    assem_debug("%s %s,%s,%s\n", name, regname[rt], regname[rs], regname[HOST_TEMPREG]);
    output_w32(op | 0x0a000000 | rm_rn_rd(HOST_TEMPREG, rs, rt));
    if (rs == HOST_TEMPREG || rt != HOST_TEMPREG)
      host_tempreg_release();
  }
  (void)name;
}

static void emit_andimm(u_int rs, u_int imm, u_int rt)
{
  if (imm == 0)
    emit_zeroreg(rt);
  else
    emit_logicop_imm(0, rs, imm, rt);
}

static void emit_orimm(u_int rs, u_int imm, u_int rt)
{
  if (imm == 0) {
    if (rs != rt)
      emit_mov(rs, rt);
  }
  else
    emit_logicop_imm(1, rs, imm, rt);
}

static void emit_xorimm(u_int rs, u_int imm, u_int rt)
{
  if (imm == 0) {
    if (rs != rt)
      emit_mov(rs, rt);
  }
  else
    emit_logicop_imm(2, rs, imm, rt);
}

static void emit_sbfm(u_int rs,u_int imm,u_int rt)
{
  assem_debug("sbfm %s,%s,#0,#%d\n",regname[rt],regname[rs],imm);
  output_w32(0x13000000 | n_immr_imms_rn_rd(0, 0, imm, rs, rt));
}

static void emit_ubfm(u_int rs,u_int imm,u_int rt)
{
  assem_debug("ubfm %s,%s,#0,#%d\n",regname[rt],regname[rs],imm);
  output_w32(0x53000000 | n_immr_imms_rn_rd(0, 0, imm, rs, rt));
}

static void emit_shlimm(u_int rs,u_int imm,u_int rt)
{
  assem_debug("lsl %s,%s,#%d\n",regname[rt],regname[rs],imm);
  output_w32(0x53000000 | n_immr_imms_rn_rd(0, (31-imm)+1, 31-imm, rs, rt));
}

static void emit_shrimm(u_int rs,u_int imm,u_int rt)
{
  assem_debug("lsr %s,%s,#%d\n",regname[rt],regname[rs],imm);
  output_w32(0x53000000 | n_immr_imms_rn_rd(0, imm, 31, rs, rt));
}

static void emit_shrimm64(u_int rs,u_int imm,u_int rt)
{
  assem_debug("lsr %s,%s,#%d\n",regname[rt],regname[rs],imm);
  output_w32(0xd3400000 | n_immr_imms_rn_rd(0, imm, 63, rs, rt));
}

static void emit_sarimm(u_int rs,u_int imm,u_int rt)
{
  assem_debug("asr %s,%s,#%d\n",regname[rt],regname[rs],imm);
  output_w32(0x13000000 | n_immr_imms_rn_rd(0, imm, 31, rs, rt));
}

static void emit_rorimm(u_int rs,u_int imm,u_int rt)
{
  assem_debug("ror %s,%s,#%d\n",regname[rt],regname[rs],imm);
  output_w32(0x13800000 | rm_imm6_rn_rd(rs, imm, rs, rt));
}

static void emit_signextend16(u_int rs, u_int rt)
{
  assem_debug("sxth %s,%s\n", regname[rt], regname[rs]);
  output_w32(0x13000000 | n_immr_imms_rn_rd(0, 0, 15, rs, rt));
}

static void emit_shl(u_int rs,u_int rshift,u_int rt)
{
  assem_debug("lsl %s,%s,%s\n",regname[rt],regname[rs],regname[rshift]);
  output_w32(0x1ac02000 | rm_rn_rd(rshift, rs, rt));
}

static void emit_shr(u_int rs,u_int rshift,u_int rt)
{
  assem_debug("lsr %s,%s,%s\n",regname[rt],regname[rs],regname[rshift]);
  output_w32(0x1ac02400 | rm_rn_rd(rshift, rs, rt));
}

static void emit_sar(u_int rs,u_int rshift,u_int rt)
{
  assem_debug("asr %s,%s,%s\n",regname[rt],regname[rs],regname[rshift]);
  output_w32(0x1ac02800 | rm_rn_rd(rshift, rs, rt));
}

static void emit_cmpimm(u_int rs, u_int imm)
{
  if (imm < 4096) {
    assem_debug("cmp %s,%#x\n", regname[rs], imm);
    output_w32(0x71000000 | imm12_rn_rd(imm, rs, WZR));
  }
  else if (-imm < 4096) {
    assem_debug("cmn %s,%#x\n", regname[rs], imm);
    output_w32(0x31000000 | imm12_rn_rd(-imm, rs, WZR));
  }
  else if (imm < 16777216 && !(imm & 0xfff)) {
    assem_debug("cmp %s,#%#x\n", regname[rs], imm);
    output_w32(0x71400000 | imm12_rn_rd(imm >> 12, rs, WZR));
  }
  else {
    host_tempreg_acquire();
    emit_movimm(imm, HOST_TEMPREG);
    assem_debug("cmp %s,%s\n", regname[rs], regname[HOST_TEMPREG]);
    output_w32(0x6b000000 | rm_rn_rd(HOST_TEMPREG, rs, WZR));
    host_tempreg_release();
  }
}

static void emit_cmov_imm(u_int cond0, u_int cond1, u_int imm, u_int rt)
{
  assert(imm == 0 || imm == 1);
  assert(cond0 < 0x10);
  assert(cond1 < 0x10);
  if (imm) {
    assem_debug("csinc %s,%s,%s,%s\n",regname[rt],regname[rt],regname[WZR],condname[cond1]);
    output_w32(0x1a800400 | (cond1 << 12) | rm_rn_rd(WZR, rt, rt));
  } else {
    assem_debug("csel %s,%s,%s,%s\n",regname[rt],regname[WZR],regname[rt],condname[cond0]);
    output_w32(0x1a800000 | (cond0 << 12) | rm_rn_rd(rt, WZR, rt));
  }
}

static void emit_cmovne_imm(u_int imm,u_int rt)
{
  emit_cmov_imm(COND_NE, COND_EQ, imm, rt);
}

static void emit_cmovl_imm(u_int imm,u_int rt)
{
  emit_cmov_imm(COND_LT, COND_GE, imm, rt);
}

static void emit_cmovb_imm(int imm,u_int rt)
{
  emit_cmov_imm(COND_CC, COND_CS, imm, rt);
}

static void emit_cmoveq_reg(u_int rs,u_int rt)
{
  assem_debug("csel %s,%s,%s,eq\n",regname[rt],regname[rs],regname[rt]);
  output_w32(0x1a800000 | (COND_EQ << 12) | rm_rn_rd(rt, rs, rt));
}

static void emit_cmovne_reg(u_int rs,u_int rt)
{
  assem_debug("csel %s,%s,%s,ne\n",regname[rt],regname[rs],regname[rt]);
  output_w32(0x1a800000 | (COND_NE << 12) | rm_rn_rd(rt, rs, rt));
}

static void emit_cmovl_reg(u_int rs,u_int rt)
{
  assem_debug("csel %s,%s,%s,lt\n",regname[rt],regname[rs],regname[rt]);
  output_w32(0x1a800000 | (COND_LT << 12) | rm_rn_rd(rt, rs, rt));
}

static void emit_cmovb_reg(u_int rs,u_int rt)
{
  assem_debug("csel %s,%s,%s,cc\n",regname[rt],regname[rs],regname[rt]);
  output_w32(0x1a800000 | (COND_CC << 12) | rm_rn_rd(rt, rs, rt));
}

static void emit_cmovs_reg(u_int rs,u_int rt)
{
  assem_debug("csel %s,%s,%s,mi\n",regname[rt],regname[rs],regname[rt]);
  output_w32(0x1a800000 | (COND_MI << 12) | rm_rn_rd(rt, rs, rt));
}

static void emit_csinvle_reg(u_int rs1,u_int rs2,u_int rt)
{
  assem_debug("csinv %s,%s,%s,le\n",regname[rt],regname[rs1],regname[rs2]);
  output_w32(0x5a800000 | (COND_LE << 12) | rm_rn_rd(rs2, rs1, rt));
}

static void emit_csinvne_reg(u_int rs1,u_int rs2,u_int rt)
{
  assem_debug("csinv %s,%s,%s,ne\n",regname[rt],regname[rs1],regname[rs2]);
  output_w32(0x5a800000 | (COND_NE << 12) | rm_rn_rd(rs2, rs1, rt));
}

static void emit_slti32(u_int rs,int imm,u_int rt)
{
  if(rs!=rt) emit_zeroreg(rt);
  emit_cmpimm(rs,imm);
  if(rs==rt) emit_movimm(0,rt);
  emit_cmovl_imm(1,rt);
}

static void emit_sltiu32(u_int rs,int imm,u_int rt)
{
  if(rs!=rt) emit_zeroreg(rt);
  emit_cmpimm(rs,imm);
  if(rs==rt) emit_movimm(0,rt);
  emit_cmovb_imm(1,rt);
}

static void emit_cmp(u_int rs,u_int rt)
{
  assem_debug("cmp %s,%s\n",regname[rs],regname[rt]);
  output_w32(0x6b000000 | rm_rn_rd(rt, rs, WZR));
}

static void emit_cmpcs(u_int rs,u_int rt)
{
  assem_debug("ccmp %s,%s,#0,cs\n",regname[rs],regname[rt]);
  output_w32(0x7a400000 | (COND_CS << 12) | rm_rn_rd(rt, rs, 0));
}

static void emit_set_gz32(u_int rs, u_int rt)
{
  //assem_debug("set_gz32\n");
  emit_cmpimm(rs,1);
  emit_movimm(1,rt);
  emit_cmovl_imm(0,rt);
}

static void emit_set_nz32(u_int rs, u_int rt)
{
  //assem_debug("set_nz32\n");
  if(rs!=rt) emit_mov(rs,rt);
  emit_test(rs,rs);
  emit_cmovne_imm(1,rt);
}

static void emit_set_if_less32(u_int rs1, u_int rs2, u_int rt)
{
  //assem_debug("set if less (%%%s,%%%s),%%%s\n",regname[rs1],regname[rs2],regname[rt]);
  if(rs1!=rt&&rs2!=rt) emit_zeroreg(rt);
  emit_cmp(rs1,rs2);
  if(rs1==rt||rs2==rt) emit_movimm(0,rt);
  emit_cmovl_imm(1,rt);
}

static void emit_set_if_carry32(u_int rs1, u_int rs2, u_int rt)
{
  //assem_debug("set if carry (%%%s,%%%s),%%%s\n",regname[rs1],regname[rs2],regname[rt]);
  if(rs1!=rt&&rs2!=rt) emit_zeroreg(rt);
  emit_cmp(rs1,rs2);
  if(rs1==rt||rs2==rt) emit_movimm(0,rt);
  emit_cmovb_imm(1,rt);
}

static int can_jump_or_call(const void *a)
{
  intptr_t diff = (u_char *)a - out;
  return (-134217728 <= diff && diff <= 134217727);
}

static void emit_call(const void *a)
{
  intptr_t diff = (u_char *)a - out;
  assem_debug("bl %p (%p+%lx)%s\n", a, out, diff, func_name(a));
  assert(!(diff & 3));
  if (-134217728 <= diff && diff <= 134217727)
    output_w32(0x94000000 | ((diff >> 2) & 0x03ffffff));
  else
    abort();
}

static void emit_jmp(const void *a)
{
  assem_debug("b %p (%p+%lx)%s\n", a, out, (u_char *)a - out, func_name(a));
  u_int offset = genjmp(a);
  output_w32(0x14000000 | offset);
}

static void emit_jne(const void *a)
{
  assem_debug("bne %p\n", a);
  u_int offset = genjmpcc(a);
  output_w32(0x54000000 | (offset << 5) | COND_NE);
}

static void emit_jeq(const void *a)
{
  assem_debug("beq %p\n", a);
  u_int offset = genjmpcc(a);
  output_w32(0x54000000 | (offset << 5) | COND_EQ);
}

static void emit_js(const void *a)
{
  assem_debug("bmi %p\n", a);
  u_int offset = genjmpcc(a);
  output_w32(0x54000000 | (offset << 5) | COND_MI);
}

static void emit_jns(const void *a)
{
  assem_debug("bpl %p\n", a);
  u_int offset = genjmpcc(a);
  output_w32(0x54000000 | (offset << 5) | COND_PL);
}

static void emit_jl(const void *a)
{
  assem_debug("blt %p\n", a);
  u_int offset = genjmpcc(a);
  output_w32(0x54000000 | (offset << 5) | COND_LT);
}

static void emit_jge(const void *a)
{
  assem_debug("bge %p\n", a);
  u_int offset = genjmpcc(a);
  output_w32(0x54000000 | (offset << 5) | COND_GE);
}

static void emit_jo(const void *a)
{
  assem_debug("bvs %p\n", a);
  u_int offset = genjmpcc(a);
  output_w32(0x54000000 | (offset << 5) | COND_VS);
}

static void emit_jno(const void *a)
{
  assem_debug("bvc %p\n", a);
  u_int offset = genjmpcc(a);
  output_w32(0x54000000 | (offset << 5) | COND_VC);
}

static void emit_jc(const void *a)
{
  assem_debug("bcs %p\n", a);
  u_int offset = genjmpcc(a);
  output_w32(0x54000000 | (offset << 5) | COND_CS);
}

static void emit_cb(u_int isnz, u_int is64, const void *a, u_int r)
{
  assem_debug("cb%sz %s,%p\n", isnz?"n":"", is64?regname64[r]:regname[r], a);
  u_int offset = genjmpcc(a);
  is64 = is64 ? 0x80000000 : 0;
  isnz = isnz ? 0x01000000 : 0;
  output_w32(0x34000000 | is64 | isnz | imm19_rt(offset, r));
}

static void *emit_cbz(u_int r, const void *a)
{
  void *ret = out;
  emit_cb(0, 0, a, r);
  return ret;
}

static void emit_jmpreg(u_int r)
{
  assem_debug("br %s\n", regname64[r]);
  output_w32(0xd61f0000 | rm_rn_rd(0, r, 0));
}

static void emit_retreg(u_int r)
{
  assem_debug("ret %s\n", r == LR ? "" : regname64[r]);
  output_w32(0xd65f0000 | rm_rn_rd(0, r, 0));
}

static void emit_ret(void)
{
  emit_retreg(LR);
}

static void emit_adr(void *addr, u_int rt)
{
  intptr_t offset = (u_char *)addr - out;
  assert(-1048576 <= offset && offset < 1048576);
  assert(rt < 31);
  assem_debug("adr x%d,#%#lx\n", rt, offset);
  output_w32(0x10000000 | ((offset&0x3) << 29) | (((offset>>2)&0x7ffff) << 5) | rt);
}

static void emit_adrp(void *addr, u_int rt)
{
  intptr_t offset = ((intptr_t)addr & ~0xfffl) - ((intptr_t)out & ~0xfffl);
  assert(-4294967296l <= offset && offset < 4294967296l);
  assert(rt < 31);
  offset >>= 12;
  assem_debug("adrp %s,#%#lx(000)\n",regname64[rt],offset);
  output_w32(0x90000000 | ((offset&0x3)<<29) | (((offset>>2)&0x7ffff)<<5) | rt);
}

static void emit_readword_indexed(int offset, u_int rs, u_int rt)
{
  assem_debug("ldur %s,[%s+%#x]\n",regname[rt],regname64[rs],offset);
  assert(-256 <= offset && offset < 256);
  output_w32(0xb8400000 | imm9_rn_rt(offset&0x1ff, rs, rt));
}

static void emit_strb_dualindexed(u_int rs1, u_int rs2, u_int rt)
{
  assem_debug("strb %s, [%s,%s]\n",regname[rt],regname64[rs1],regname[rs2]);
  output_w32(0x38204800 | rm_rn_rd(rs2, rs1, rt));
}

static void emit_strh_dualindexed(u_int rs1, u_int rs2, u_int rt)
{
  assem_debug("strh %s, [%s,%s]\n",regname[rt],regname64[rs1],regname[rs2]);
  output_w32(0x78204800 | rm_rn_rd(rs2, rs1, rt));
}

static void emit_str_dualindexed(u_int rs1, u_int rs2, u_int rt)
{
  assem_debug("str %s, [%s,%s]\n",regname[rt],regname64[rs1],regname[rs2]);
  output_w32(0xb8204800 | rm_rn_rd(rs2, rs1, rt));
}

static void emit_readdword_dualindexedx8(u_int rs1, u_int rs2, u_int rt)
{
  assem_debug("ldr %s, [%s,%s, uxtw #3]\n",regname64[rt],regname64[rs1],regname[rs2]);
  output_w32(0xf8605800 | rm_rn_rd(rs2, rs1, rt));
}
#define emit_readptr_dualindexedx_ptrlen emit_readdword_dualindexedx8

static void emit_ldrb_dualindexed(u_int rs1, u_int rs2, u_int rt)
{
  assem_debug("ldrb %s, [%s,%s]\n",regname[rt],regname64[rs1],regname[rs2]);
  output_w32(0x38604800 | rm_rn_rd(rs2, rs1, rt));
}

static void emit_ldrsb_dualindexed(u_int rs1, u_int rs2, u_int rt)
{
  assem_debug("ldrsb %s, [%s,%s]\n",regname[rt],regname64[rs1],regname[rs2]);
  output_w32(0x38a04800 | rm_rn_rd(rs2, rs1, rt));
}

static void emit_ldrh_dualindexed(u_int rs1, u_int rs2, u_int rt)
{
  assem_debug("ldrh %s, [%s,%s, uxtw]\n",regname[rt],regname64[rs1],regname[rs2]);
  output_w32(0x78604800 | rm_rn_rd(rs2, rs1, rt));
}

static void emit_ldrsh_dualindexed(u_int rs1, u_int rs2, u_int rt)
{
  assem_debug("ldrsh %s, [%s,%s, uxtw]\n",regname[rt],regname64[rs1],regname[rs2]);
  output_w32(0x78a04800 | rm_rn_rd(rs2, rs1, rt));
}

static void emit_ldr_dualindexed(u_int rs1, u_int rs2, u_int rt)
{
  assem_debug("ldr %s, [%s,%s, uxtw]\n",regname[rt],regname64[rs1],regname[rs2]);
  output_w32(0xb8604800 | rm_rn_rd(rs2, rs1, rt));
}

static void emit_movsbl_indexed(int offset, u_int rs, u_int rt)
{
  assem_debug("ldursb %s,[%s+%#x]\n",regname[rt],regname64[rs],offset);
  assert(-256 <= offset && offset < 256);
  output_w32(0x38c00000 | imm9_rn_rt(offset&0x1ff, rs, rt));
}

static void emit_movswl_indexed(int offset, u_int rs, u_int rt)
{
  assem_debug("ldursh %s,[%s+%#x]\n",regname[rt],regname64[rs],offset);
  assert(-256 <= offset && offset < 256);
  output_w32(0x78c00000 | imm9_rn_rt(offset&0x1ff, rs, rt));
}

static void emit_movzbl_indexed(int offset, u_int rs, u_int rt)
{
  assem_debug("ldurb %s,[%s+%#x]\n",regname[rt],regname64[rs],offset);
  assert(-256 <= offset && offset < 256);
  output_w32(0x38400000 | imm9_rn_rt(offset&0x1ff, rs, rt));
}

static void emit_movzwl_indexed(int offset, u_int rs, u_int rt)
{
  assem_debug("ldurh %s,[%s+%#x]\n",regname[rt],regname64[rs],offset);
  assert(-256 <= offset && offset < 256);
  output_w32(0x78400000 | imm9_rn_rt(offset&0x1ff, rs, rt));
}

static void emit_writeword_indexed(u_int rt, int offset, u_int rs)
{
  if (!(offset & 3) && (u_int)offset <= 16380) {
    assem_debug("str %s,[%s+%#x]\n", regname[rt], regname[rs], offset);
    output_w32(0xb9000000 | imm12_rn_rd(offset >> 2, rs, rt));
  }
  else if (-256 <= offset && offset < 256) {
    assem_debug("stur %s,[%s+%#x]\n", regname[rt], regname[rs], offset);
    output_w32(0xb8000000 | imm9_rn_rt(offset & 0x1ff, rs, rt));
  }
  else
    assert(0);
}

static void emit_writehword_indexed(u_int rt, int offset, u_int rs)
{
  if (!(offset & 1) && (u_int)offset <= 8190) {
    assem_debug("strh %s,[%s+%#x]\n", regname[rt], regname64[rs], offset);
    output_w32(0x79000000 | imm12_rn_rd(offset >> 1, rs, rt));
  }
  else if (-256 <= offset && offset < 256) {
    assem_debug("sturh %s,[%s+%#x]\n", regname[rt], regname64[rs], offset);
    output_w32(0x78000000 | imm9_rn_rt(offset & 0x1ff, rs, rt));
  }
  else
    assert(0);
}

static void emit_writebyte_indexed(u_int rt, int offset, u_int rs)
{
  if ((u_int)offset < 4096) {
    assem_debug("strb %s,[%s+%#x]\n", regname[rt], regname64[rs], offset);
    output_w32(0x39000000 | imm12_rn_rd(offset, rs, rt));
  }
  else if (-256 <= offset && offset < 256) {
    assem_debug("sturb %s,[%s+%#x]\n", regname[rt], regname64[rs], offset);
    output_w32(0x38000000 | imm9_rn_rt(offset & 0x1ff, rs, rt));
  }
  else
    assert(0);
}

static void emit_umull(u_int rs1, u_int rs2, u_int rt)
{
  assem_debug("umull %s,%s,%s\n",regname64[rt],regname[rs1],regname[rs2]);
  output_w32(0x9ba00000 | rm_ra_rn_rd(rs2, WZR, rs1, rt));
}

static void emit_smull(u_int rs1, u_int rs2, u_int rt)
{
  assem_debug("smull %s,%s,%s\n",regname64[rt],regname[rs1],regname[rs2]);
  output_w32(0x9b200000 | rm_ra_rn_rd(rs2, WZR, rs1, rt));
}

static void emit_msub(u_int rs1, u_int rs2, u_int rs3, u_int rt)
{
  assem_debug("msub %s,%s,%s,%s\n",regname[rt],regname[rs1],regname[rs2],regname[rs3]);
  output_w32(0x1b008000 | rm_ra_rn_rd(rs2, rs3, rs1, rt));
}

static void emit_sdiv(u_int rs1, u_int rs2, u_int rt)
{
  assem_debug("sdiv %s,%s,%s\n",regname[rt],regname[rs1],regname[rs2]);
  output_w32(0x1ac00c00 | rm_rn_rd(rs2, rs1, rt));
}

static void emit_udiv(u_int rs1, u_int rs2, u_int rt)
{
  assem_debug("udiv %s,%s,%s\n",regname[rt],regname[rs1],regname[rs2]);
  output_w32(0x1ac00800 | rm_rn_rd(rs2, rs1, rt));
}

static void emit_clz(u_int rs, u_int rt)
{
  assem_debug("clz %s,%s\n",regname[rt],regname[rs]);
  output_w32(0x5ac01000 | rn_rd(rs, rt));
}

// special case for checking invalid_code
static void emit_ldrb_indexedsr12_reg(u_int rbase, u_int r, u_int rt)
{
  emit_shrimm(r, 12, rt);
  assem_debug("ldrb %s,[%s,%s,uxtw]\n",regname[rt],regname64[rbase],regname[rt]);
  output_w32(0x38604800 | rm_rn_rd(rt, rbase, rt));
}

// special for loadlr_assemble, rs2 is destroyed
static void emit_bic_lsl(u_int rs1,u_int rs2,u_int shift,u_int rt)
{
  emit_shl(rs2, shift, rs2);
  emit_bic(rs1, rs2, rt);
}

static void emit_bic_lsr(u_int rs1,u_int rs2,u_int shift,u_int rt)
{
  emit_shr(rs2, shift, rs2);
  emit_bic(rs1, rs2, rt);
}

static void emit_ldst(int is_st, int is64, u_int rt, u_int rn, u_int ofs)
{
  u_int op = 0xb9000000;
  attr_unused const char *ldst = is_st ? "st" : "ld";
  attr_unused char rp = is64 ? 'x' : 'w';
  assem_debug("%sr %c%d,[x%d,#%#x]\n", ldst, rp, rt, rn, ofs);
  is64 = is64 ? 1 : 0;
  assert((ofs & ((1 << (2+is64)) - 1)) == 0);
  ofs = (ofs >> (2+is64));
  if (!is_st) op |= 0x00400000;
  if (is64)   op |= 0x40000000;
  output_w32(op | imm12_rn_rd(ofs, rn, rt));
}

static void emit_ldstp(int is_st, int is64, u_int rt1, u_int rt2, u_int rn, int ofs)
{
  u_int op = 0x29000000;
  attr_unused const char *ldst = is_st ? "st" : "ld";
  attr_unused char rp = is64 ? 'x' : 'w';
  assem_debug("%sp %c%d,%c%d,[x%d,#%#x]\n", ldst, rp, rt1, rp, rt2, rn, ofs);
  is64 = is64 ? 1 : 0;
  assert((ofs & ((1 << (2+is64)) - 1)) == 0);
  ofs = (ofs >> (2+is64));
  assert(-64 <= ofs && ofs <= 63);
  ofs &= 0x7f;
  if (!is_st) op |= 0x00400000;
  if (is64)   op |= 0x80000000;
  output_w32(op | imm7_rt2_rn_rt(ofs, rt2, rn, rt1));
}

static void save_load_regs_all(int is_store, u_int reglist)
{
  int ofs = 0, c = 0;
  u_int r, pair[2];
  for (r = 0; reglist; r++, reglist >>= 1) {
    if (reglist & 1)
      pair[c++] = r;
    if (c == 2) {
      emit_ldstp(is_store, 1, pair[0], pair[1], SP, SSP_CALLEE_REGS + ofs);
      ofs += 8 * 2;
      c = 0;
    }
  }
  if (c) {
    emit_ldst(is_store, 1, pair[0], SP, SSP_CALLEE_REGS + ofs);
    ofs += 8;
  }
  assert(ofs <= SSP_CALLER_REGS);
}

// Save registers before function call
static void save_regs(u_int reglist)
{
  reglist &= CALLER_SAVE_REGS; // only save the caller-save registers
  save_load_regs_all(1, reglist);
}

// Restore registers after function call
static void restore_regs(u_int reglist)
{
  reglist &= CALLER_SAVE_REGS;
  save_load_regs_all(0, reglist);
}

/* Stubs/epilogue */

static void literal_pool(int n)
{
  (void)literals;
}

static void literal_pool_jumpover(int n)
{
}

// parsed by get_pointer, find_extjump_insn
static void emit_extjump(u_char *addr, u_int target)
{
  assert(((addr[3]&0xfc)==0x14) || ((addr[3]&0xff)==0x54)); // b or b.cond

  emit_movz(target & 0xffff, 0);
  emit_movk_lsl16(target >> 16, 0);

  // addr is in the current recompiled block (max 256k)
  // offset shouldn't exceed +/-1MB
  emit_adr(addr, 1);
  emit_far_jump(dyna_linker);
}

static void check_extjump2(void *src)
{
  u_int *ptr = src;
  assert((ptr[0] & 0xffe0001f) == 0x52800000); // movz r0, #val
  (void)ptr;
}

// put rt_val into rt, potentially making use of rs with value rs_val
static void emit_movimm_from(u_int rs_val, u_int rs, u_int rt_val, u_int rt)
{
  int diff = rt_val - rs_val;
  if ((-4096 < diff && diff < 4096)
      || (-16777216 < diff && diff < 16777216 && !(diff & 0xfff)))
    emit_addimm(rs, diff, rt);
  else if (rt_val == ~rs_val)
    emit_not(rs, rt);
  else if (is_rotated_mask(rs_val ^ rt_val))
    emit_xorimm(rs, rs_val ^ rt_val, rt);
  else
    emit_movimm(rt_val, rt);
}

// return 1 if the above function can do it's job cheaply
static int is_similar_value(u_int v1, u_int v2)
{
  int diff = v1 - v2;
  return (-4096 < diff && diff < 4096)
    || (-16777216 < diff && diff < 16777216 && !(diff & 0xfff))
    || v1 == ~v2
    || is_rotated_mask(v1 ^ v2);
}

static void emit_movimm_from64(u_int rs_val, u_int rs, uintptr_t rt_val, u_int rt)
{
  if (rt_val < 0x100000000ull) {
    emit_movimm_from(rs_val, rs, rt_val, rt);
    return;
  }
  // just move the whole thing. At least on Linux all addresses
  // seem to be 48bit, so 3 insns - not great not terrible
  emit_movimm64(rt_val, rt);
}

// trashes x2
static void pass_args64(u_int a0, u_int a1)
{
  if(a0==1&&a1==0) {
    // must swap
    emit_mov64(a0,2); emit_mov64(a1,1); emit_mov64(2,0);
  }
  else if(a0!=0&&a1==0) {
    emit_mov64(a1,1);
    if (a0>=0) emit_mov64(a0,0);
  }
  else {
    if(a0>=0&&a0!=0) emit_mov64(a0,0);
    if(a1>=0&&a1!=1) emit_mov64(a1,1);
  }
}

static void loadstore_extend(enum stub_type type, u_int rs, u_int rt)
{
  switch(type) {
    case LOADB_STUB:  emit_sbfm(rs, 7, rt); break;
    case LOADBU_STUB:
    case STOREB_STUB: emit_ubfm(rs, 7, rt); break;
    case LOADH_STUB:  emit_sbfm(rs, 15, rt); break;
    case LOADHU_STUB:
    case STOREH_STUB: emit_ubfm(rs, 15, rt); break;
    case LOADW_STUB:  
    case STOREW_STUB: if (rs != rt) emit_mov(rs, rt); break;
    default:          assert(0);
  }
}

#include "pcsxmem.h"
//#include "pcsxmem_inline.c"

static void do_readstub(int n)
{
  assem_debug("do_readstub %x\n",start+stubs[n].a*4);
  set_jump_target(stubs[n].addr, out);
  enum stub_type type = stubs[n].type;
  int i = stubs[n].a;
  int rs = stubs[n].b;
  const struct regstat *i_regs = (void *)stubs[n].c;
  int adj = (int)stubs[n].d;
  u_int reglist = stubs[n].e;
  const signed char *i_regmap = i_regs->regmap;
  int rt;
  if(dops[i].itype==C2LS||dops[i].itype==LOADLR) {
    rt=get_reg(i_regmap,FTEMP);
  }else{
    rt=get_reg(i_regmap,dops[i].rt1);
  }
  assert(rs>=0);
  int r,temp=-1,temp2=HOST_TEMPREG,regs_saved=0;
  void *restore_jump = NULL, *handler_jump = NULL;
  reglist|=(1<<rs);
  for (r = 0; r < HOST_CCREG; r++) {
    if (r != EXCLUDE_REG && ((1 << r) & reglist) == 0) {
      temp = r;
      break;
    }
  }
  if(rt>=0&&dops[i].rt1!=0)
    reglist&=~(1<<rt);
  if(temp==-1) {
    save_regs(reglist);
    regs_saved=1;
    temp=(rs==0)?2:0;
  }
  if((regs_saved||(reglist&2)==0)&&temp!=1&&rs!=1)
    temp2=1;
  emit_readdword(&mem_rtab,temp);
  emit_shrimm(rs,12,temp2);
  emit_readdword_dualindexedx8(temp,temp2,temp2);
  emit_adds64(temp2,temp2,temp2);
  handler_jump=out;
  emit_jc(0);
  if(dops[i].itype==C2LS||(rt>=0&&dops[i].rt1!=0)) {
    switch(type) {
      case LOADB_STUB:  emit_ldrsb_dualindexed(temp2,rs,rt); break;
      case LOADBU_STUB: emit_ldrb_dualindexed(temp2,rs,rt); break;
      case LOADH_STUB:  emit_ldrsh_dualindexed(temp2,rs,rt); break;
      case LOADHU_STUB: emit_ldrh_dualindexed(temp2,rs,rt); break;
      case LOADW_STUB:  emit_ldr_dualindexed(temp2,rs,rt); break;
      default:          assert(0);
    }
  }
  if(regs_saved) {
    restore_jump=out;
    emit_jmp(0); // jump to reg restore
  }
  else
    emit_jmp(stubs[n].retaddr); // return address
  set_jump_target(handler_jump, out);

  if(!regs_saved)
    save_regs(reglist);
  void *handler=NULL;
  if(type==LOADB_STUB||type==LOADBU_STUB)
    handler=jump_handler_read8;
  if(type==LOADH_STUB||type==LOADHU_STUB)
    handler=jump_handler_read16;
  if(type==LOADW_STUB)
    handler=jump_handler_read32;
  assert(handler);
  pass_args64(rs,temp2);
  int cc, cc_use;
  cc = cc_use = get_reg(i_regmap, CCREG);
  if (cc < 0)
    emit_loadreg(CCREG, (cc_use = 2));
  emit_addimm(cc_use, adj, 2);

  emit_far_call(handler);

#if 0
  // cycle reload for read32 only (value in w2 both in and out)
  if (type == LOADW_STUB) {
    emit_addimm(2, -adj, cc_use);
    if (cc < 0)
      emit_storereg(CCREG, cc_use);
  }
#endif
  if(dops[i].itype==C2LS||(rt>=0&&dops[i].rt1!=0)) {
    loadstore_extend(type,0,rt);
  }
  if(restore_jump)
    set_jump_target(restore_jump, out);
  restore_regs(reglist);
  emit_jmp(stubs[n].retaddr);
}

static void inline_readstub(enum stub_type type, int i, u_int addr,
  const signed char regmap[], int target, int adj, u_int reglist)
{
  int ra = cinfo[i].addr;
  int rt = get_reg(regmap, target);
  assert(ra >= 0);
  u_int is_dynamic=0;
  uintptr_t host_addr = 0;
  void *handler;
  int cc, cc_use;
  cc = cc_use = get_reg(regmap, CCREG);
  //if(pcsx_direct_read(type,addr,adj,cc,target?ra:-1,rt))
  //  return;
  handler = get_direct_memhandler(mem_rtab, addr, type, &host_addr);
  if (handler == NULL) {
    if(rt<0||dops[i].rt1==0)
      return;
    if (addr != host_addr)
      emit_movimm_from64(addr, ra, host_addr, ra);
    switch(type) {
      case LOADB_STUB:  emit_movsbl_indexed(0,ra,rt); break;
      case LOADBU_STUB: emit_movzbl_indexed(0,ra,rt); break;
      case LOADH_STUB:  emit_movswl_indexed(0,ra,rt); break;
      case LOADHU_STUB: emit_movzwl_indexed(0,ra,rt); break;
      case LOADW_STUB:  emit_readword_indexed(0,ra,rt); break;
      default:          assert(0);
    }
    return;
  }
  is_dynamic = pcsxmem_is_handler_dynamic(addr);
  if (is_dynamic) {
    if(type==LOADB_STUB||type==LOADBU_STUB)
      handler=jump_handler_read8;
    if(type==LOADH_STUB||type==LOADHU_STUB)
      handler=jump_handler_read16;
    if(type==LOADW_STUB)
      handler=jump_handler_read32;
  }

  // call a memhandler
  if(rt>=0&&dops[i].rt1!=0)
    reglist&=~(1<<rt);
  save_regs(reglist);
  if(target==0)
    emit_movimm(addr,0);
  else if(ra!=0)
    emit_mov(ra,0);
  if (cc < 0)
    emit_loadreg(CCREG, (cc_use = 2));
  emit_addimm(cc_use, adj, 2);
  if(is_dynamic) {
    uintptr_t l1 = ((uintptr_t *)mem_rtab)[addr>>12] << 1;
    intptr_t offset = (l1 & ~0xfffl) - ((intptr_t)out & ~0xfffl);
    if (-4294967296l <= offset && offset < 4294967296l) {
      emit_adrp((void *)l1, 1);
      emit_addimm64(1, l1 & 0xfff, 1);
    }
    else
      emit_movimm64(l1, 1);
  }
  else
    emit_far_call(do_memhandler_pre);

  emit_far_call(handler);

#if 0
  // cycle reload for read32 only (value in w2 both in and out)
  if (type == LOADW_STUB) {
    if (!is_dynamic)
      emit_far_call(do_memhandler_post);
    emit_addimm(2, -adj, cc_use);
    if (cc < 0)
      emit_storereg(CCREG, cc_use);
  }
#endif
  if(rt>=0&&dops[i].rt1!=0)
    loadstore_extend(type, 0, rt);
  restore_regs(reglist);
}

static void do_writestub(int n)
{
  assem_debug("do_writestub %x\n",start+stubs[n].a*4);
  set_jump_target(stubs[n].addr, out);
  enum stub_type type=stubs[n].type;
  int i=stubs[n].a;
  int rs=stubs[n].b;
  struct regstat *i_regs=(struct regstat *)stubs[n].c;
  int adj = (int)stubs[n].d;
  u_int reglist=stubs[n].e;
  signed char *i_regmap=i_regs->regmap;
  int rt,r;
  if(dops[i].itype==C2LS) {
    rt=get_reg(i_regmap,r=FTEMP);
  }else{
    rt=get_reg(i_regmap,r=dops[i].rs2);
  }
  assert(rs>=0);
  assert(rt>=0);
  int rtmp,temp=-1,temp2,regs_saved=0;
  void *restore_jump = NULL, *handler_jump = NULL;
  int reglist2=reglist|(1<<rs)|(1<<rt);
  for (rtmp = 0; rtmp < HOST_CCREG; rtmp++) {
    if (rtmp != EXCLUDE_REG && ((1 << rtmp) & reglist) == 0) {
      temp = rtmp;
      break;
    }
  }
  if(temp==-1) {
    save_regs(reglist);
    regs_saved=1;
    for(rtmp=0;rtmp<=3;rtmp++)
      if(rtmp!=rs&&rtmp!=rt)
        {temp=rtmp;break;}
  }
  if((regs_saved||(reglist2&8)==0)&&temp!=3&&rs!=3&&rt!=3)
    temp2=3;
  else {
    host_tempreg_acquire();
    temp2=HOST_TEMPREG;
  }
  emit_readdword(&mem_wtab,temp);
  emit_shrimm(rs,12,temp2);
  emit_readdword_dualindexedx8(temp,temp2,temp2);
  emit_adds64(temp2,temp2,temp2);
  handler_jump=out;
  emit_jc(0);
  switch(type) {
    case STOREB_STUB: emit_strb_dualindexed(temp2,rs,rt); break;
    case STOREH_STUB: emit_strh_dualindexed(temp2,rs,rt); break;
    case STOREW_STUB: emit_str_dualindexed(temp2,rs,rt); break;
    default:          assert(0);
  }
  if(regs_saved) {
    restore_jump=out;
    emit_jmp(0); // jump to reg restore
  }
  else
    emit_jmp(stubs[n].retaddr); // return address (invcode check)
  set_jump_target(handler_jump, out);

  if(!regs_saved)
    save_regs(reglist);
  void *handler=NULL;
  switch(type) {
    case STOREB_STUB: handler=jump_handler_write8; break;
    case STOREH_STUB: handler=jump_handler_write16; break;
    case STOREW_STUB: handler=jump_handler_write32; break;
    default:          assert(0);
  }
  assert(handler);
  pass_args(rs,rt);
  if(temp2!=3) {
    emit_mov64(temp2,3);
    host_tempreg_release();
  }
  int cc, cc_use;
  cc = cc_use = get_reg(i_regmap, CCREG);
  if (cc < 0)
    emit_loadreg(CCREG, (cc_use = 2));
  emit_addimm(cc_use, adj, 2);

  emit_far_call(handler);

  // new cycle_count returned in x2
  emit_addimm(2, -adj, cc_use);
  if (cc < 0)
    emit_storereg(CCREG, cc_use);
  if (restore_jump)
    set_jump_target(restore_jump, out);
  restore_regs(reglist);
  emit_jmp(stubs[n].retaddr);
}

static void inline_writestub(enum stub_type type, int i, u_int addr,
  const signed char regmap[], int target, int adj, u_int reglist)
{
  int ra = cinfo[i].addr;
  int rt = get_reg(regmap,target);
  assert(ra >= 0);
  assert(rt >= 0);
  uintptr_t host_addr = 0;
  void *handler = get_direct_memhandler(mem_wtab, addr, type, &host_addr);
  if (handler == NULL) {
    if (addr != host_addr)
      emit_movimm_from64(addr, ra, host_addr, ra);
    switch (type) {
      case STOREB_STUB: emit_writebyte_indexed(rt, 0, ra); break;
      case STOREH_STUB: emit_writehword_indexed(rt, 0, ra); break;
      case STOREW_STUB: emit_writeword_indexed(rt, 0, ra); break;
      default:          assert(0);
    }
    return;
  }

  // call a memhandler
  save_regs(reglist);
  emit_writeword(ra, &address); // some handlers still need it
  loadstore_extend(type, rt, 0);
  int cc, cc_use;
  cc = cc_use = get_reg(regmap, CCREG);
  if (cc < 0)
    emit_loadreg(CCREG, (cc_use = 2));
  emit_addimm(cc_use, adj, 2);

  emit_far_call(do_memhandler_pre);
  emit_far_call(handler);
  emit_far_call(do_memhandler_post);
  emit_addimm(2, -adj, cc_use);
  if (cc < 0)
    emit_storereg(CCREG, cc_use);
  restore_regs(reglist);
}

/* Special assem */

static void c2op_prologue(u_int op, int i, const struct regstat *i_regs, u_int reglist)
{
  save_load_regs_all(1, reglist);
  cop2_do_stall_check(op, i, i_regs, 0);
#ifdef PCNT
  emit_movimm(op, 0);
  emit_far_call(pcnt_gte_start);
#endif
  // pointer to cop2 regs
  emit_addimm64(FP, (u_char *)&psxRegs.CP2D.r[0] - (u_char *)&dynarec_local, 0);
}

static void c2op_epilogue(u_int op,u_int reglist)
{
#ifdef PCNT
  emit_movimm(op, 0);
  emit_far_call(pcnt_gte_end);
#endif
  save_load_regs_all(0, reglist);
}

static void c2op_assemble(int i, const struct regstat *i_regs)
{
  u_int c2op=source[i]&0x3f;
  u_int hr,reglist_full=0,reglist;
  int need_flags,need_ir;
  for(hr=0;hr<HOST_REGS;hr++) {
    if(i_regs->regmap[hr]>=0) reglist_full|=1<<hr;
  }
  reglist=reglist_full&CALLER_SAVE_REGS;

  if (gte_handlers[c2op]!=NULL) {
    need_flags=!(gte_unneeded[i+1]>>63); // +1 because of how liveness detection works
    need_ir=(gte_unneeded[i+1]&0xe00)!=0xe00;
    assem_debug("gte op %08x, unneeded %016lx, need_flags %d, need_ir %d\n",
      source[i],gte_unneeded[i+1],need_flags,need_ir);
    if(HACK_ENABLED(NDHACK_GTE_NO_FLAGS))
      need_flags=0;
    //int shift = (source[i] >> 19) & 1;
    //int lm = (source[i] >> 10) & 1;
    switch(c2op) {
      default:
        (void)need_ir;
        c2op_prologue(c2op, i, i_regs, reglist);
        emit_movimm(source[i],1); // opcode
        emit_writeword(1,&psxRegs.code);
        emit_far_call(need_flags?gte_handlers[c2op]:gte_handlers_nf[c2op]);
        break;
    }
    c2op_epilogue(c2op,reglist);
  }
}

static void c2op_ctc2_31_assemble(signed char sl, signed char temp)
{
  //value = value & 0x7ffff000;
  //if (value & 0x7f87e000) value |= 0x80000000;
  emit_andimm(sl, 0x7fffe000, temp);
  emit_testimm(temp, 0xff87ffff);
  emit_andimm(sl, 0x7ffff000, temp);
  host_tempreg_acquire();
  emit_orimm(temp, 0x80000000, HOST_TEMPREG);
  emit_cmovne_reg(HOST_TEMPREG, temp);
  host_tempreg_release();
  assert(0); // testing needed
}

static void do_mfc2_31_one(u_int copr,signed char temp)
{
  emit_readshword(&reg_cop2d[copr],temp);
  emit_bicsar_imm(temp,31,temp);
  emit_cmpimm(temp,0xf80);
  emit_csinvle_reg(temp,WZR,temp); // if (temp > 0xf80) temp = ~0;
  emit_andimm(temp,0xf80,temp);
}

static void c2op_mfc2_29_assemble(signed char tl, signed char temp)
{
  if (temp < 0) {
    host_tempreg_acquire();
    temp = HOST_TEMPREG;
  }
  do_mfc2_31_one(9,temp);
  emit_shrimm(temp,7,tl);
  do_mfc2_31_one(10,temp);
  emit_orrshr_imm(temp,2,tl);
  do_mfc2_31_one(11,temp);
  emit_orrshl_imm(temp,3,tl);
  emit_writeword(tl,&reg_cop2d[29]);

  if (temp == HOST_TEMPREG)
    host_tempreg_release();
}

static void multdiv_assemble_arm64(int i, const struct regstat *i_regs)
{
  //  case 0x18: MULT
  //  case 0x19: MULTU
  //  case 0x1A: DIV
  //  case 0x1B: DIVU
  if(dops[i].rs1&&dops[i].rs2)
  {
    switch(dops[i].opcode2)
    {
    case 0x18: // MULT
    case 0x19: // MULTU
      {
        signed char m1=get_reg(i_regs->regmap,dops[i].rs1);
        signed char m2=get_reg(i_regs->regmap,dops[i].rs2);
        signed char hi=get_reg(i_regs->regmap,HIREG);
        signed char lo=get_reg(i_regs->regmap,LOREG);
        assert(m1>=0);
        assert(m2>=0);
        assert(hi>=0);
        assert(lo>=0);

        if(dops[i].opcode2==0x18) // MULT
          emit_smull(m1,m2,hi);
        else                 // MULTU
          emit_umull(m1,m2,hi);

        emit_mov(hi,lo);
        emit_shrimm64(hi,32,hi);
        break;
      }
    case 0x1A: // DIV
    case 0x1B: // DIVU
      {
        signed char numerator=get_reg(i_regs->regmap,dops[i].rs1);
        signed char denominator=get_reg(i_regs->regmap,dops[i].rs2);
        signed char quotient=get_reg(i_regs->regmap,LOREG);
        signed char remainder=get_reg(i_regs->regmap,HIREG);
        assert(numerator>=0);
        assert(denominator>=0);
        assert(quotient>=0);
        assert(remainder>=0);

        if (dops[i].opcode2 == 0x1A) // DIV
          emit_sdiv(numerator,denominator,quotient);
        else                    // DIVU
          emit_udiv(numerator,denominator,quotient);
        emit_msub(quotient,denominator,numerator,remainder);

        // div 0 quotient (remainder is already correct)
        host_tempreg_acquire();
        if (dops[i].opcode2 == 0x1A) { // DIV
          emit_add_lsrimm(WZR,numerator,31,HOST_TEMPREG);
          emit_orn_asrimm(HOST_TEMPREG,numerator,31,HOST_TEMPREG);
        }
        else
          emit_movimm(~0,HOST_TEMPREG);
        emit_test(denominator,denominator);
        emit_cmoveq_reg(HOST_TEMPREG,quotient);
        host_tempreg_release();
        break;
      }
    default:
      assert(0);
    }
  }
  else
  {
    signed char hr=get_reg(i_regs->regmap,HIREG);
    signed char lr=get_reg(i_regs->regmap,LOREG);
    if ((dops[i].opcode2==0x1A || dops[i].opcode2==0x1B) && dops[i].rs2==0) // div 0
    {
      if (dops[i].rs1) {
        signed char numerator = get_reg(i_regs->regmap, dops[i].rs1);
        assert(numerator >= 0);
        if (hr >= 0)
          emit_mov(numerator,hr);
        if (lr >= 0) {
          if (dops[i].opcode2 == 0x1A) { // DIV
            emit_add_lsrimm(WZR,numerator,31,lr);
            emit_orn_asrimm(lr,numerator,31,lr);
          }
          else
            emit_movimm(~0,lr);
        }
      }
      else {
        if (hr >= 0) emit_zeroreg(hr);
        if (lr >= 0) emit_movimm(~0,lr);
      }
    }
    else if ((dops[i].opcode2==0x1A || dops[i].opcode2==0x1B) && dops[i].rs1==0)
    {
      signed char denominator = get_reg(i_regs->regmap, dops[i].rs2);
      assert(denominator >= 0);
      if (hr >= 0) emit_zeroreg(hr);
      if (lr >= 0) {
        emit_zeroreg(lr);
        emit_test(denominator, denominator);
        emit_csinvne_reg(lr, lr, lr);
      }
    }
    else
    {
      // Multiply by zero is zero.
      if (hr >= 0) emit_zeroreg(hr);
      if (lr >= 0) emit_zeroreg(lr);
    }
  }
}
#define multdiv_assemble multdiv_assemble_arm64

// wb_dirtys making use of stp when possible
static void wb_dirtys(const signed char i_regmap[], u_int i_dirty)
{
  signed char mregs[34+1];
  int r, hr;
  memset(mregs, -1, sizeof(mregs));
  for (hr = 0; hr < HOST_REGS; hr++) {
    r = i_regmap[hr];
    if (hr == EXCLUDE_REG || r <= 0 || r == CCREG)
      continue;
    if (!((i_dirty >> hr) & 1))
      continue;
    assert(r < 34u);
    mregs[r] = hr;
  }
  for (r = 1; r < 34; r++) {
    if (mregs[r] < 0)
      continue;
    if (mregs[r+1] >= 0) {
      uintptr_t offset = (u_char *)&psxRegs.GPR.r[r] - (u_char *)&dynarec_local;
      emit_ldstp(1, 0, mregs[r], mregs[r+1], FP, offset);
      r++;
    }
    else
      emit_storereg(r, mregs[r]);
  }
}
#define wb_dirtys wb_dirtys

static void load_all_regs(const signed char i_regmap[])
{
  signed char mregs[34+1];
  int r, hr;
  memset(mregs, -1, sizeof(mregs));
  for (hr = 0; hr < HOST_REGS; hr++) {
    r = i_regmap[hr];
    if (hr == EXCLUDE_REG || r < 0 || r == CCREG)
      continue;
    if ((u_int)r < 34u)
      mregs[r] = hr;
    else if (r < TEMPREG)
      emit_loadreg(r, hr);
  }
  if (mregs[0] >= 0)
    emit_zeroreg(mregs[0]); // we could use arm64's ZR instead of reg alloc
  for (r = 1; r < 34; r++) {
    if (mregs[r] < 0)
      continue;
    if (mregs[r+1] >= 0) {
      uintptr_t offset = (u_char *)&psxRegs.GPR.r[r] - (u_char *)&dynarec_local;
      emit_ldstp(0, 0, mregs[r], mregs[r+1], FP, offset);
      r++;
    }
    else
      emit_loadreg(r, mregs[r]);
  }
}
#define load_all_regs load_all_regs

static void do_jump_vaddr(u_int rs)
{
  if (rs != 0)
    emit_mov(rs, 0);
  emit_readptr(&hash_table_ptr, 1);
  emit_far_call(ndrc_get_addr_ht);
  emit_jmpreg(0);
}

static void do_preload_rhash(u_int r) {
  // Don't need this for ARM.  On x86, this puts the value 0xf8 into the
  // register.  On ARM the hash can be done with a single instruction (below)
}

static void do_preload_rhtbl(u_int ht) {
  emit_addimm64(FP, (u_char *)&mini_ht - (u_char *)&dynarec_local, ht);
}

static void do_rhash(u_int rs,u_int rh) {
  emit_andimm(rs, 0xf8, rh);
}

static void do_miniht_load(int ht, u_int rh) {
  emit_add64(ht, rh, ht);
  emit_ldst(0, 0, rh, ht, 0);
}

static void do_miniht_jump(u_int rs, u_int rh, u_int ht) {
  emit_cmp(rh, rs);
  void *jaddr = out;
  emit_jeq(0);
  do_jump_vaddr(rs);

  set_jump_target(jaddr, out);
  assem_debug("ldr %s,[%s,#8]\n",regname64[ht], regname64[ht]);
  output_w32(0xf9400000 | imm12_rn_rd(8 >> 3, ht, ht));
  emit_jmpreg(ht);
}

// parsed by set_jump_target?
static void do_miniht_insert(u_int return_address,u_int rt,int temp) {
  emit_movz_lsl16((return_address>>16)&0xffff,rt);
  emit_movk(return_address&0xffff,rt);
  add_to_linker(out,return_address,1);
  emit_adr(out,temp);
  emit_writedword(temp,&mini_ht[(return_address&0xFF)>>3][1]);
  emit_writeword(rt,&mini_ht[(return_address&0xFF)>>3][0]);
}

static attr_unused void clear_cache_arm64(char *start, char *end)
{
  // Don't rely on GCC's __clear_cache implementation, as it caches
  // icache/dcache cache line sizes, that can vary between cores on
  // big.LITTLE architectures.
  uint64_t addr, ctr_el0;
  static size_t icache_line_size = 0xffff, dcache_line_size = 0xffff;
  size_t isize, dsize;

  __asm__ volatile("mrs %0, ctr_el0" : "=r"(ctr_el0));
  isize = 4 << ((ctr_el0 >> 0) & 0xf);
  dsize = 4 << ((ctr_el0 >> 16) & 0xf);

  // use the global minimum cache line size
  icache_line_size = isize = icache_line_size < isize ? icache_line_size : isize;
  dcache_line_size = dsize = dcache_line_size < dsize ? dcache_line_size : dsize;

  /* If CTR_EL0.IDC is enabled, Data cache clean to the Point of Unification is
     not required for instruction to data coherence.  */
  if ((ctr_el0 & (1 << 28)) == 0x0) {
    addr = (uint64_t)start & ~(uint64_t)(dsize - 1);
    for (; addr < (uint64_t)end; addr += dsize)
      // use "civac" instead of "cvau", as this is the suggested workaround for
      // Cortex-A53 errata 819472, 826319, 827319 and 824069.
      __asm__ volatile("dc civac, %0" : : "r"(addr) : "memory");
  }
  __asm__ volatile("dsb ish" : : : "memory");

  /* If CTR_EL0.DIC is enabled, Instruction cache cleaning to the Point of
     Unification is not required for instruction to data coherence.  */
  if ((ctr_el0 & (1 << 29)) == 0x0) {
    addr = (uint64_t)start & ~(uint64_t)(isize - 1);
    for (; addr < (uint64_t)end; addr += isize)
      __asm__ volatile("ic ivau, %0" : : "r"(addr) : "memory");

    __asm__ volatile("dsb ish" : : : "memory");
  }

  __asm__ volatile("isb" : : : "memory");
}

// CPU-architecture-specific initialization
static void arch_init(void)
{
  uintptr_t diff = (u_char *)&ndrc->tramp.f - (u_char *)&ndrc->tramp.ops;
  struct tramp_insns *ops = NDRC_WRITE_OFFSET(ndrc->tramp.ops);
  size_t i;
  assert(!(diff & 3));
  start_tcache_write(ops, (u_char *)ops + sizeof(ndrc->tramp.ops));
  for (i = 0; i < ARRAY_SIZE(ndrc->tramp.ops); i++) {
    ops[i].ldr = 0x58000000 | imm19_rt(diff >> 2, 17); // ldr x17, [=val]
    ops[i].br  = 0xd61f0000 | rm_rn_rd(0, 17, 0);      // br x17
  }
  end_tcache_write(ops, (u_char *)ops + sizeof(ndrc->tramp.ops));
}

// vim:shiftwidth=2:expandtab
